const fs = require("fs");
const path = require("path");
// 使用read和write操作buffer数据一次不能处理过多数据，否则会占用过多内存
// 可以读取一部分，写一部分
const SIZE = 6;
let buffer = Buffer.alloc(SIZE);
fs.open(path.join(__dirname, "x.txt"), "r", function (err, rfd) {
  fs.open(path.join(__dirname, "note.txt"), "w", function (err, wfd) {
    let readOffset = 0;
    let writeOffset = 0;
    function next() {
      // 每次读取数据的长度为SIZE，从readOffset开始读取
      fs.read(rfd, buffer, 0, SIZE, readOffset, function (err, bytesRead) {
        if (bytesRead === 0) {
          fs.close(rfd, () => {});
          fs.close(wfd, () => {});
          return null;
        }
        // 写入数据，从0开头到bytesRead个长度，
        // write的参数 fd: number, buffer: Buffer, offset: number【写入数据buffer的起始位置】, length: number【写入数据buffer的长度】, position: number, callback:
        fs.write(wfd, buffer, 0, bytesRead, writeOffset, function (err) {
          readOffset += bytesRead;
          writeOffset += bytesRead;
          if (!err) {
            next();
          }
        });
      });
    }
    next();
  });
});
